﻿using CommonUtils;
using System.Linq;

namespace CodeAssistant.Commands.Wpf
{
    //按位置给代码排序
    internal class GridElement
    {
        public string Xml;

        public static int GridHeight = 400;
        public static int GridWidth = 300;

        public int MarginLeft;
        public int MarginTop;

        public GridElement(string xml)
        {
            Xml = xml;
            var margin = xml.GetBetween("Margin=\"", "\"", false);
            var marginElements = margin.SplitByComma();
            MarginLeft = marginElements[0].ToInt();
            MarginTop = marginElements[1].ToInt();
            var marginRight = marginElements[2].ToInt();
            var marginBottom = marginElements[3].ToInt();

            var horizontalAlignment = xml.GetBetween("HorizontalAlignment=\"", "\"", false);
            var width = xml.GetBetween("Width=\"", "\"", false).ToInt();
            if (horizontalAlignment == "Center")
            {
                MarginLeft = MarginLeft + GridWidth / 2 - width / 2;
                Xml = Xml.Replace("HorizontalAlignment=\"Center\"", "HorizontalAlignment=\"Left\"");
                var newMargin = StringUtil.Join(MarginLeft, MarginTop, marginRight, marginBottom);
                Xml = Xml.Replace(margin, newMargin);
                margin = newMargin;
            }
            var verticalAlignment = xml.GetBetween("VerticalAlignment=\"", "\"", false);
            var height = xml.GetBetween("Height=\"", "\"", false).ToInt();
            if (verticalAlignment == "Center")
            {
                MarginTop = MarginTop + GridHeight / 2 - height / 2;
                Xml = Xml.Replace("VerticalAlignment=\"Center\"", "VerticalAlignment=\"Top\"");
                var newMargin = StringUtil.Join(MarginLeft, MarginTop, marginRight, marginBottom);
                Xml = Xml.Replace(margin, newMargin);
            }
        }

        public static GridElement[] GetElements(string[] elementXmls)
        => elementXmls.Select(m => new GridElement(m)).ToArray();

        public static GridElement[] GetElements(string gridXml)
        {
            var elementXmls = gridXml.GetBetweens("<", "/>", true);
            return GetElements(elementXmls);
        }
    }
}
